/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nus.application.web.base.inteceptor;

import com.nus.application.web.base.annotation.SessionInject;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import java.lang.reflect.Field;
import java.util.Map;

/**
 *
 * @author robin.foe
 */
public class SessionInterceptor extends AbstractInterceptor{
    
    public SessionInterceptor(){super();}
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Map<String, Object> session = invocation.getInvocationContext().getSession();
		Object actionObject = invocation.getAction();
		Class<?> klass = actionObject.getClass();
		
		while(true){
			if(klass == null || klass.getName().endsWith("ActionSupport"))
				break;

			Field[] fields = klass.getDeclaredFields();
			for(Field field : fields){
				if(field.getAnnotation(SessionInject.class)!=null){
					String sessionId = field.getAnnotation(SessionInject.class).sessionId();
					Object sessionObject = session.get(sessionId);
					if(sessionObject == null && field.getAnnotation(SessionInject.class).autoCreate())
						sessionObject = field.getType().getConstructor().newInstance();
					
					field.setAccessible(true);
					field.set(actionObject, sessionObject);
					field.setAccessible(false);
				}
			}
			klass = klass.getSuperclass();
		}
		
		return invocation.invoke();
	}
    
}
